package com.example.community.controller;

import com.example.community.dao.pojo.*;
import com.example.community.event.EventProducer;
import com.example.community.service.CommentService;
import com.example.community.service.DiscussPostService;
import com.example.community.service.LikeService;
import com.example.community.service.UserService;
import com.example.community.uitls.CommunityConstant;
import com.example.community.uitls.CommunityUtil;
import com.example.community.uitls.HostHolder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.*;

import static com.example.community.uitls.CommunityConstant.ENTITY_TYPE_COMMENT;
import static com.example.community.uitls.CommunityConstant.ENTITY_TYPE_POST;

/**
 * @ClassName: DiscussPostController
 * @Description:
 * @Author
 * @Date 2022-03-19
 * @Version 1.0
 */
@Controller
@RequestMapping("discuss")
public class DiscussPostController implements CommunityConstant {

    @Autowired
    DiscussPostService discussPostService;

    @Autowired
    private HostHolder hostHolder;

    @Autowired
    private UserService userService;

    @Autowired
    private CommentService commentService;

    @Autowired
    private LikeService likeService;

    @Autowired
    private EventProducer eventProducer;


    @PostMapping("add")
    @ResponseBody
    public String addDiscussPost(String title, String content){
        User user = hostHolder.getUser();
        if (user == null){
            return CommunityUtil.getJSONString(403, "你还没有登录哦!");
        }

        DiscussPost post = new DiscussPost();
        post.setUserId(user.getId());
        post.setTitle(title);
        post.setContent(content);
        post.setCreateTime(new Date());
        discussPostService.insertDiscussPost(post);

        //触发发贴事件，将数据上次到elasticsearch服务器中
        Event event = new Event();
        event.setTopic(TOPIC_PUBLISH)
                .setUserId(user.getId())
                .setEntityType(ENTITY_TYPE_POST)
                .setEntityId(post.getId());

        eventProducer.fireEvent(event);

        // 报错的情况,将来统一处理.
        return CommunityUtil.getJSONString(0, "发布成功!");
    }

    @GetMapping("detail/{discussPostId}")
    public String discussDetail(@PathVariable("discussPostId")int discussPostId, Model model, Page page){
        //获取帖子
        DiscussPost post = discussPostService.findDiscussPostById(discussPostId);
        model.addAttribute("post",post);
        //获取用户
        User user = userService.findUserById(post.getUserId());
        model.addAttribute("user",user);

        //点赞数量
        long likeCount = likeService.findEntityLikeCount(ENTITY_TYPE_POST,discussPostId);
        model.addAttribute("likeCount", likeCount);
        // 点赞状态(当前用户对此文章是否已经点赞)
        int likeStatus = hostHolder.getUser() == null ? 0 :
                likeService.findEntityLikeStatus(hostHolder.getUser().getId(), ENTITY_TYPE_POST, discussPostId);
        model.addAttribute("likeStatus", likeStatus);

        //评论分页设置
        page.setRows(post.getCommentCount());
        page.setLimit(5);
        page.setPath("/discuss/detail"  + discussPostId);

        //获取评论信息（分为一级评论和二级评论） 二级评论即对一级评论的回复
        //评论的内容包括 评论者的个人信息，评论的内容  用一个Map来表示一条评论
        //先获取一级评论的列表
        List<Comment> comments = commentService.selectCommentByEntity(
                ENTITY_TYPE_POST, post.getId(), page.getOffset(), page.getLimit());
        List<Map<String,Object>> commentVoList = new ArrayList<>();
        //循环遍历comments表，获取评论者的信息
        if (comments!=null){
            for (Comment comment:comments) {
                Map<String,Object> commentVo = new HashMap<>();
                commentVo.put("user",userService.findUserById(comment.getUserId()));
                commentVo.put("comment",comment);

                //评论的点赞数量，
                likeCount = likeService.findEntityLikeCount(ENTITY_TYPE_COMMENT,comment.getId());
                model.addAttribute("likeCount", likeCount);
                commentVo.put("likeCount", likeCount);
                //用户对评论点赞状态
                likeStatus = hostHolder.getUser() == null ? 0 :
                        likeService.findEntityLikeStatus(hostHolder.getUser().getId(), ENTITY_TYPE_COMMENT, comment.getId());
                commentVo.put("likeStatus", likeStatus);
                //此时 这个comment可能还会有回复，即二级评论，所以再循环查询这个comment,这个回复列表不做分页
                List<Comment> replyList = commentService.selectCommentByEntity(
                        ENTITY_TYPE_COMMENT, comment.getId(), 0, Integer.MAX_VALUE);
                List<Map<String,Object>> replyVoList = new ArrayList<>();
                for (Comment reply:replyList){
                    Map<String, Object> replyVo = new HashMap<>();
                    // 回复
                    replyVo.put("reply", reply);
                    // 作者
                    replyVo.put("user", userService.findUserById(reply.getUserId()));
                    // 回复目标
                    User target = reply.getTargetId() == 0 ? null : userService.findUserById(reply.getTargetId());
                    replyVo.put("target", target);
                    // 评论的回复的点赞数量
                    likeCount = likeService.findEntityLikeCount(ENTITY_TYPE_COMMENT, reply.getId());
                    replyVo.put("likeCount", likeCount);
                    // 用户对评论的回复的点赞状态
                    likeStatus = hostHolder.getUser() == null ? 0 :
                            likeService.findEntityLikeStatus(hostHolder.getUser().getId(), ENTITY_TYPE_COMMENT, reply.getId());
                    replyVo.put("likeStatus", likeStatus);
                    replyVoList.add(replyVo);
                }
                commentVo.put("replys",replyVoList);

                // 回复数量
                int replyCount = commentService.findCommentCount(ENTITY_TYPE_COMMENT, comment.getId());
                commentVo.put("replyCount", replyCount);

                commentVoList.add(commentVo);
            }
        }
        model.addAttribute("comments", commentVoList);
        return "/site/discuss-detail";
    }
}
